<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Swoole2 extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('swoole2')
            ->setDescription('the test command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->serv = new \Swoole\Server("127.0.0.1", 9502);

        $this->serv->set(array(
            'worker_num' => 2, //一般设置为服务器CPU数的1-4倍
            'daemonize' => 1, //以守护进程执行
            'task_worker_num' => 8, //task进程的数量
            "log_file" => "swoolw_task.log" ,//日志
        ));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();

    }


    //接收客户端的请求并响应
    public function onReceive($serv, $fd, $from_id, $data){

        $serv->send($fd, "SUCCESS");//返回信息给客户端
        file_put_contents(__DIR__.'/swoole2.log',date('Y-m-d H:i:s')."\r\n",FILE_APPEND);
        for ($i=0;$i<8;$i++){
            $serv->task($data);//投递任务
        }


    }

    public function onTask($serv, $task_id, $from_id, $data)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $num = $redis->LLEN($data);
        for($i=0;$i< ($num / 8);$i++){
            $str = $redis->RPOP($data);
            \Db::table('swoole_test_2')->insert(['str'=>$str,'created_at'=>date('Y-m-d H:i:s')]);
        }

        return true;

    }

    //任务执行完自动回调结束方法
    public function onFinish($serv, $task_id, $data)
    {

        file_put_contents(__DIR__.'/swoole2.log',date('Y-m-d H:i:s')."\r\n",FILE_APPEND);
    }













}
